package com.crcode.crm.controller.user;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.crcode.crm.bean.role.RoleUserBean;
import com.crcode.crm.bean.user.UserBean;
import com.crcode.crm.service.role.RoleUserService;
import com.crcode.crm.service.user.UserService;
import com.crcode.crm.utils.DateUtil;
import com.crcode.crm.utils.Object2Map;
import com.crcode.crm.utils.PageVo;
import com.crcode.crm.utils.ResultPageUtil;
import com.crcode.crm.utils.ResultUtil;

/**
 * 用户控制层
 * 
 * @author lxw
 * @date 2019年1月18日
 */
@Controller
public class UserController {
	@Resource(name = "userService")
	private UserService userService;

	@Resource(name = "roleUserService")
	private RoleUserService roleUserService;

	/**
	 * 登录
	 * 
	 * @author lxw
	 * @date 2019年1月22日
	 * @param request
	 * @param loginName
	 * @param pwd
	 * @return
	 */
	@RequestMapping(value = "/user/login", method = RequestMethod.POST)
	@ResponseBody
	public ResultUtil login(HttpServletRequest request, HttpSession session, String loginName, String pwd) {

		ResultUtil ru = new ResultUtil();
		UserBean user = this.userService.findByLoginName(loginName);
		if (user == null) {
			ru.setInfo("登录名错误！");
			ru.setObj(null);
			ru.setStatus(false);
			return ru;
		}
		if (!user.getLoginPwd().equals(pwd)) {
			ru.setInfo("密码错误！");
			ru.setObj(null);
			ru.setStatus(false);
			return ru;
		}
		if(user.getIsUse()==0){
			ru.setInfo("账户已停用，请线下联系管理员！");
			ru.setObj(null);
			ru.setStatus(false);
			return ru;
		}
		user.setLastLoginTime(DateUtil.DateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
		this.userService.updateResultBean(user);

		session.setAttribute("user", JSONObject.toJSONString(user));
		ru.setInfo("登录成功！");
		ru.setObj(user);
		ru.setStatus(true);
		return ru;
	}

	/**
	 * 获取session
	 * 
	 * @author lxw
	 * @date 2019年2月14日
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/user/getSession", method = RequestMethod.POST)
	@ResponseBody
	public ResultUtil getSession(HttpServletRequest request, HttpSession session) {

		ResultUtil ru = new ResultUtil();
		Object obj = session.getAttribute("user");
		if (obj != null) {
			UserBean user = JSONObject.parseObject(obj.toString(), UserBean.class);
			ru.setObj(user);
		}

		ru.setInfo("登录成功！");
		ru.setStatus(obj != null);
		return ru;
	}

	/**
	 * 用户分页展示
	 * 
	 * @author lxw
	 * @date 2019年1月18日
	 * @param request
	 * @param user
	 * @param vo
	 * @return
	 */
	@RequestMapping(value = "/user/loadUserPage", method = RequestMethod.POST)
	@ResponseBody
	public ResultPageUtil loadUserPage(HttpServletRequest request, UserBean user, PageVo vo) {

		return this.userService.findAll(user, vo);
	}

	/**
	 * 新增编辑保存用户
	 * 
	 * @author lxw
	 * @date 2019年1月18日
	 * @param request
	 * @param user
	 * @param roleUuid
	 * @param depUuid
	 * @return
	 */
	@RequestMapping(value = "/user/addOrEditSaveUser", method = RequestMethod.POST)
	@ResponseBody
	public ResultUtil addOrEditSaveUser(HttpServletRequest request, UserBean user, String roleUuid) {

		ResultUtil ru = new ResultUtil();

		boolean is = false;
		// 1、新增
		if (user.getId() == null) {
			UserBean u = this.userService.findByLoginName(user.getLoginName());
			if (u != null) {
				ru.setInfo("操作失败，登录名称已存在!");
				ru.setStatus(is);
				ru.setObj(null);
				return ru;
			}
			is = this.userService.saveResultBoolean(user);
			// 保存用户角色关系
			if (is && StringUtils.isNotEmpty(roleUuid)) {
				List<RoleUserBean> rul = new ArrayList<>();
				for(String str :roleUuid.split(",")){
					RoleUserBean roleU = new RoleUserBean();
					roleU.setRoleUuid(str);
					roleU.setUserUuid(user.getUuid());
					rul.add(roleU);
				}
				this.roleUserService.beathSaveResultBoolean(rul);
			}
			ru.setInfo(is ? "操作成功！" : "操作失败!");
			ru.setStatus(is);
			ru.setObj(user);
			return ru;
		}
		// 2、编辑保存,UUID\ID\loginName不可修改
		UserBean old_u = this.userService.findByUuid(user.getUuid());
		old_u.setUserContactAdress(user.getUserContactAdress());
		old_u.setUserContactPhone(user.getUserContactPhone());
		old_u.setUserRealName(user.getUserRealName());
		old_u.setSex(user.getSex());
		old_u.setIsUse(user.getIsUse());
		old_u.setUserIdNumber(user.getUserIdNumber());
		old_u.setUserContactEmail(user.getUserContactEmail());
		is = this.userService.updateResultBoolean(old_u);
		// 保存用户角色关系
		if (is) {
			this.roleUserService.deleteByUserUuid(user.getUuid());
			if (StringUtils.isNotEmpty(roleUuid)) {
				List<RoleUserBean> rul = new ArrayList<>();
				for(String str :roleUuid.split(",")){
					RoleUserBean roleU = new RoleUserBean();
					roleU.setRoleUuid(str);
					roleU.setUserUuid(user.getUuid());
					rul.add(roleU);
				}
				this.roleUserService.beathSaveResultBoolean(rul);
			}
		}
		ru.setInfo(is ? "操作成功！" : "操作失败!");
		ru.setStatus(is);
		ru.setObj(user);
		return ru;
	}

	/**
	 * 改变用户启用/停用
	 * 
	 * @author lxw
	 * @date 2018年9月18日 下午4:30:16
	 * @param request
	 * @param uuids
	 * @param isUse
	 *            0、停用；1、启用；
	 * @return
	 */
	@RequestMapping(value = "/user/setIsUseByUserUuids", method = RequestMethod.POST)
	@ResponseBody
	public ResultUtil setIsUseByUserUuids(HttpServletRequest request, String uuids, Integer isUse) {
		ResultUtil ru = new ResultUtil();
		String[] arr = uuids.split(",");
		boolean is = false;
		for (String str : arr) {
			UserBean user = this.userService.findByUuid(str);
			user.setIsUse(isUse);
			is = this.userService.updateResultBoolean(user);
		}
		ru.setInfo(is ? "设定成功！" : "设定失败！");
		ru.setStatus(is);
		return ru;
	}

	/**
	 * 管理员重置用户信息
	 * 
	 * @author lxw
	 * @date 2019年3月28日
	 * @param request
	 * @param uuids
	 * @return
	 */
	@RequestMapping(value = "/user/resetInfoByUserUuids", method = RequestMethod.POST)
	@ResponseBody
	public ResultUtil resetInfoByUserUuids(HttpServletRequest request, String uuids) {
		ResultUtil ru = new ResultUtil();
		String[] arr = uuids.split(",");
		boolean is = false;
		for (String str : arr) {
			UserBean user = this.userService.findByUuid(str);
			user.setIsFull(0);
			user.setLastLoginTime(null);
			user.setIsUse(1);
			user.setLoginPwd("123456");
			user.setSex(1);
			user.setUserContactAdress(null);
			user.setUserContactEmail(null);
			user.setUserContactPhone(null);
			user.setUserIdNumber(null);
			user.setUserNickName(user.getLoginName());
			user.setUserRealName(user.getLoginName());
			is = this.userService.updateResultBoolean(user);
			this.roleUserService.deleteByUserUuid(user.getUuid());
		}
		ru.setInfo(is ? "设定成功！" : "设定失败！");
		ru.setStatus(is);
		return ru;
	}

	/**
	 * 根据UUID查询个人详细信息
	 * 
	 * @author lxw
	 * @date 2019年1月18日
	 * @param request
	 * @param uuid
	 * @return
	 */
	@RequestMapping(value = "/user/findUserInfoByUuid", method = RequestMethod.POST)
	@ResponseBody
	public UserBean findUserInfoByUuid(HttpServletRequest request, String uuid) {

		return this.userService.findByUuid(uuid);
	}

	/**
	 * 根据UUID查询个人信息附带角色部门信息
	 * 
	 * @author lxw
	 * @date 2019年2月19日
	 * @param request
	 * @param uuid
	 * @return
	 */
	@RequestMapping(value = "/user/findInfoByUuid", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> findInfoByUuid(HttpServletRequest request, String uuid) {
		UserBean user = this.userService.findByUuid(uuid);
		Map<String, Object> map = Object2Map.object2Map(user);
		List<String> roleUuids = this.roleUserService.getRoleUuidsByUserUuid(uuid);
		if (!roleUuids.isEmpty()) {
			map.put("roleUuid", String.join(",", roleUuids));
		} else {
			map.put("roleUuid", null);
		}
		return map;
	}

	/**
	 * 用户自己编辑信息
	 * 
	 * @author lxw
	 * @date 2019年2月20日
	 * @param request
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/user/editMyInfo", method = RequestMethod.POST)
	@ResponseBody
	public ResultUtil editMyInfo(HttpServletRequest request, UserBean user, HttpSession session) {
		ResultUtil ru = new ResultUtil();
		UserBean oldUser = this.userService.findByUuid(user.getUuid());
		oldUser.setUserRealName(user.getUserRealName());
		oldUser.setSex(user.getSex());
		oldUser.setUserIdNumber(user.getUserIdNumber());
		oldUser.setUserContactPhone(user.getUserContactPhone());
		oldUser.setUserContactEmail(user.getUserContactEmail());
		oldUser.setUserContactAdress(user.getUserContactAdress());
		oldUser.setIsFull(1);
		boolean is = this.userService.updateResultBoolean(oldUser);
		if (is) {
			session.setAttribute("user", JSONObject.toJSONString(oldUser));
		}
		ru.setInfo(is ? "操作成功！" : "操作失败！");
		ru.setObj(oldUser);
		ru.setStatus(is);
		return ru;
	}

	/**
	 * 当前登录者自己更改密码
	 * 
	 * @author lxw
	 * @date 2019年3月29日
	 * @param request
	 * @param oldPwd
	 *            输入的原密码
	 * @param newPwd
	 *            输入的新密码
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/user/editPassword", method = RequestMethod.POST)
	@ResponseBody
	public ResultUtil editPassword(HttpServletRequest request, String oldPwd, String newPwd, HttpSession session) {
		ResultUtil ru = new ResultUtil();
		Object obj = session.getAttribute("user");
		UserBean user = JSONObject.parseObject(obj.toString(), UserBean.class);
		if (!user.getLoginPwd().equals(oldPwd)) {
			ru.setInfo("操作失败，原密码错误！");
			ru.setStatus(false);
			return ru;
		}
		user.setLoginPwd(newPwd);
		boolean is = this.userService.updateResultBoolean(user);
		if (is) {
			session.setAttribute("user", JSONObject.toJSONString(user));
		}
		ru.setInfo(is ? "操作成功！" : "操作失败！");
		ru.setObj(user);
		ru.setStatus(is);
		return ru;
	}

	/**
	 * 根据UUIDS删除用户
	 * 
	 * @author lxw
	 * @date 2019年1月18日
	 * @param request
	 * @param uuids
	 * @return
	 */
	@RequestMapping(value = "/user/deleteUsersByUuIds", method = RequestMethod.POST)
	@ResponseBody
	public ResultUtil deleteUsersByUuIds(HttpServletRequest request, String uuids) {
		ResultUtil ru = new ResultUtil();
		String[] arr = uuids.split(",");
		List<String> ul = Arrays.asList(arr);
		boolean is = false;
		// 删除角色用户关联
		is = this.roleUserService.deleteByUserUuidIn(ul);
		if (!is) {
			ru.setInfo("操作失败!");
			ru.setStatus(is);
			ru.setObj(null);
			return ru;
		}
		// 删除用户
		is = this.userService.deleteUserByUuids(ul);
		ru.setInfo(is ? "操作成功！" : "操作失败!");
		ru.setStatus(is);
		ru.setObj(null);
		return ru;
	}

	/**
	 * 退出/注销
	 * 
	 * @author cl
	 * @date 2018年8月28日 上午10:16:44
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/user/loginOut", method = RequestMethod.POST)
	@ResponseBody
	public boolean loginOutSystem(HttpServletRequest request, HttpSession session) {
		session.setAttribute("user", null);
		return true;
	}

	/**
	 * 查询用户列表
	 * 
	 * @author lxw
	 * @date 2019年4月1日
	 * @param isUse
	 *            1、可以，0、不可用
	 * @return
	 */
	@RequestMapping(value = "/user/loadUserByIsUse", method = RequestMethod.POST)
	@ResponseBody
	public List<Map<String, Object>> loadUserByIsUse(HttpServletRequest request, Integer isUse) {

		return this.userService.loadUserByIsUse(isUse);
	}
}
